<script setup>
import { useUserStore } from '@/stores/user';
import JWeixin from 'weixin-js-sdk';
import { Toast, Dialog } from 'vant';

import { queryUrlParam } from '@/utils/tools';
import { EiInfo } from '@eplat/ei';
// 调用4j的service
import api4j from '@/api/example';
const router = useRouter();
const user = useUserStore();
const loading = ref(false);
const loadings = ref(false);
const finish = ref(false);
const page = reactive({
  pageSize: 10,
  currentPage: 0,
  result: []
});
// 授权
// JWeixin.config({
//   debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
//   appId: api4j.APPID, // 必填，公众号的唯一标识
//   timestamp: '', // 必填，生成签名的时间戳
//   nonceStr: '', // 必填，生成签名的随机串
//   signature: '', // 必填，签名
//   jsApiList: [] // 必填，需要使用的JS接口列表
// });
// JWeixin.ready(async () => {
//   // 获取用户code
//   const code = queryUrlParam('code');
//   // 没有授权code
//   if (code == null) {
//     // Toast('授权失败');
//     // 跳转到授权页面
//     window.location.href =
//       'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
//       api4j.APPID +
//       '&redirect_uri=https%3A%2F%2F' +
//       api4j.SERVER_DOMAIN +
//       '%2F%23%2FWX%2FWD%2FWXWD10&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
//   } else {
//     // 本地没有token新授权
//     if (user.getToken == '' || user.getToken == undefined) {
//       // Toast('正在授权');
//       const postEiInfo = new EiInfo();
//       postEiInfo.set('code', code);
//       // 通过code获取用户信息
//       await api4j.wxLogin(postEiInfo).then((res) => {
//         // 如果授权无效 重新授权
//         if (res.status !== 1) {
//           // Toast(res.msg);
//           window.location.href =
//             'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
//             api4j.APPID +
//             '&redirect_uri=https%3A%2F%2F' +
//             api4j.SERVER_DOMAIN +
//             '%2F%23%2FWX%2FWD%2FWXWD10&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
//           applyList();
//           return;
//         }
//         // Toast(res.msg);
//         // token info存放本地
//         user.setUserInfo(
//           res.extAttr.token,
//           res.extAttr.userInfo.attrs.headimgurl,
//           res.extAttr.userInfo.attrs.nickname
//         );
//         user.setUserNameTel(res.extAttr.username, res.extAttr.phone);
//         applyList();
//       });
//     }
//   }
// });

JWeixin.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
  appId: api4j.APPID1, // 必填，公众号的唯一标识
  timestamp: '', // 必填，生成签名的时间戳
  nonceStr: '', // 必填，生成签名的随机串
  signature: '', // 必填，签名
  jsApiList: [] // 必填，需要使用的JS接口列表
});
JWeixin.ready(async () => {
  // 获取用户code
  const code = queryUrlParam('code');
  // 没有授权code
  if (code == null) {
    // Toast('授权失败');
    // 跳转到授权页面
    window.location.href =
        'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
        api4j.APPID1 +
        '&redirect_uri=https%3A%2F%2F' +
        api4j.SERVER_DOMAIN1 +
        '%2F%23%2FWX%2FWD%2FWXWD12&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
  } else {
    // 本地没有token新授权
    if (user.getToken == '' || user.getToken == undefined) {
      // Toast('正在授权');
      const postEiInfo = new EiInfo();
      postEiInfo.set('code', code);
      // 通过code获取用户信息
      await api4j.wxLogins(postEiInfo).then((res) => {
        // 如果授权无效 重新授权
        if (res.status !== 1) {
          // Toast(res.msg)
          window.location.href =
              'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
              api4j.APPID1 +
              '&redirect_uri=https%3A%2F%2F' +
              api4j.SERVER_DOMAIN1 +
              '%2F%23%2FWX%2FWD%2FWXWD12&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect&forcePopup=true';
          return;
        }
        // Toast(res.msg);
        // token info存放本地
        user.setUserInfo(
            res.extAttr.token,
            res.extAttr.userInfo.attrs.headimgurl,
            res.extAttr.userInfo.attrs.nickname
        );
        user.setUserNameTel(res.extAttr.username, res.extAttr.phone);

        onLoad();
      });
    }
  }
});


const data = ref([]);
// 限流开关
const flag = ref(true);
const onLoad = async () => {
  loading.value = true;
  if (flag.value) {
    applyList();
  }
  loading.value = false;
};

const applyList = async () => {
  loadings.value = true;
  flag.value = false;
  const postEiInfo = new EiInfo();
  postEiInfo.set('token', user.getToken);
  await api4j
    .RCRM0103_zcZJOrder(postEiInfo)
    .then((res) => {
      if (res.status === 1) {
        // flag.value = true;

        // selectSum总金额
        for (let i = 0; i < res.extAttr.order.length; i++) {
          res.extAttr.order[i].selectSum = 0;
        }
        // selectOrder订单
        for (let i = 0; i < res.extAttr.order.length; i++) {
          res.extAttr.order[i].selectOrder = [];
        }

        jsonData.value = res.extAttr.order;
        console.log('res:', jsonData.value);
      }
      loadings.value = false;
    })
    .catch((error) => {
      if (error.response && error.response.status === 429) {
        // eslint-disable-next-line no-undef
        Toast('请勿频繁操作');
      }
    });
};
const jsonData = ref([]);
// const jsonData = [
//   {
//     htName: '2写22-1、18房屋租赁合同',
//     khNmae: '重庆顺安云居电子有限公司',
//     gsName: '重庆江厦置业有限公司',
//     listData: [
//       {
//         startTime: '2024-02-10',
//         endTime: '2024-05-09',
//         je: '5000.65',
//         reserve5: 'false'
//       },
//       { startTime: '2024-05-10', endTime: '2024-09-09', je: '3263.65', reserve5: 'true' }
//     ]
//   },
//   {
//     htName: '2写22-1、18房屋租赁合同',
//     khNmae: '重庆顺安云居电子有限公司',
//     gsName: '重庆江厦徐汇有限公司',
//     listData: [
//       {
//         startTime: '2024-02-10',
//         endTime: '2024-05-09',
//         je: '5000.65',
//         reserve5: 'false'
//       },
//       { startTime: '2024-05-10', endTime: '2024-09-09', je: '3263.65', reserve5: 'true' }
//     ]
//   },
//   {
//     htName: '2写22-1、18房屋租赁合同',
//     khNmae: '重庆顺安云居电子有限公司',
//     gsName: '重庆新沙纺房屋租赁有限公司',
//     listData: [
//       {
//         startTime: '2024-02-10',
//         endTime: '2024-05-09',
//         je: '5000.65',
//         reserve5: 'false'
//       },
//       { startTime: '2024-05-10', endTime: '2024-09-09', je: '3263.65', reserve5: 'true' }
//     ]
//   }
// ];

// 缴费操作
const getOrder = async (res) => {
  if (
    res.extAttr.order == '' ||
    res.extAttr.money == '' ||
    res.extAttr.body == '' ||
    res.extAttr.remark == '' ||
    res.extAttr.ZJStatus == ''
  ) {
    Toast.fail('支付明细信息失败');
    return;
  }
  const eiInfo = new EiInfo();
  if (res.extAttr.ZJStatus == 'XSF00') {
    eiInfo.set('orgid', 'XSF00');
  }
  if (res.extAttr.ZJStatus == 'JXZY00') {
    eiInfo.set('orgid', 'JXZY00');
  }
  if (res.extAttr.ZJStatus == 'JXXH00') {
    eiInfo.set('orgid', 'JXXH00');
  }
  if (res.extAttr.ZJStatus == 'YDWY00') {
    eiInfo.set('orgid', 'YDWY00');
  }
  // 企业：XSF00=重庆新沙纺房屋租赁有限公司,JXZY00=江厦置业,JXXH00=江厦徐汇,YDWY00=渝地物业江厦星光汇
  eiInfo.set('reqsn', 'YD' + res.extAttr.order); // 订单编号
  eiInfo.set('trxamt', res.extAttr.money); // 金额：分
  eiInfo.set('returl', 'http://' + api4j.SERVER_DOMAIN + '/#/WX/wd/WXwd08');
  eiInfo.set('body', res.extAttr.body);
  eiInfo.set('remark', res.extAttr.remark);

  await api4j.RCRM0103_gozjJf(eiInfo).then((e) => {
    // console.log('reseeeee', e);
    if (e.status == 0) {
      const result = e.getBlock('result');
      let key = '';
      key = 'appid';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'cusid';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'charset';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'trxamt';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'reqsn';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'returl';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'notify_url';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'body';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'randomstr';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'remark';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'validtime';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'signtype';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      key = 'version';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));
      // key = 'paytype';
      // document.getElementById(key).value = result.getCell(0, key);
      // //console.log(result.getCell(0, key));
      key = 'sign';
      document.getElementById(key).value = result.getCell(0, key);
      // console.log(result.getCell(0, key));

      const gatewayForm = document.getElementById('gatewayForm');
      gatewayForm.submit();
    }
  });
};
const showLoadingToast = (loadingType) => {
  Toast.loading({
    forbidClick: true,
    message: '加载中...',
    loadingType,
    duration: 5000
  });
};
const itemChange = async (item, item1) => {
  let sum = 0;
  const order = [];
  let first = true;
  for (let i = 0; i < item.listData.length; i++) {
    const reserve5 = item.listData[i].reserve5;
    if (reserve5 != first && reserve5 == true) {
      Toast('请按照账单顺序进行缴费');
      item1.reserve5 = false;
      return;
    }
    if (reserve5 == true) {
      sum += item.listData[i].je;
      order.push(item.listData[i].rmrp02);
    }
    item.selectOrder = order;
    item.selectSum = sum;
    first = item.listData[i].reserve5;
  }
};
const submits = async (item) => {
  // 获取所有order和sum
  console.log('selectSum', item.selectSum);
  console.log('selectOrder', item.selectOrder);
  if (item.selectSum == 0) {
    Toast('请先勾选缴费账单');
    return;
  }
  if (item.selectOrder == []) {
    Toast('请先勾选缴费账单');
    return;
  }
  Dialog.confirm({
    title: '缴费',
    message: '确认进行缴费吗?'
  })
    .then(async () => {
      const postEiInfo = new EiInfo();
      postEiInfo.set('order', item.selectOrder);
      postEiInfo.set('money', item.selectSum.toFixed(2));
      postEiInfo.set('username', user.getUsername);
      postEiInfo.set('phone', user.getPhone);
      postEiInfo.set('token', user.getToken);
      showLoadingToast();
      await api4j.RCRM0103_zjjf(postEiInfo).then((res) => {
        console.log('resSSSS', res);
        if (res.status == 1) {
          // 传递订单和明细数据
          Toast('订单创建成功');
          getOrder(res);
          onLoad();
          return;
        }
        Toast('未查询到明细');
      });
    })
    .catch(() => {
      // on cancel
    });
};
</script>
<template>
  <div>
    <van-list
      v-model:loading="loading"
      class="working-list"
      :finished="finish"
      finished-text=""
      offset="1"
      @load="onLoad"
    >
      <div
        style="
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          background: #4b75e5;
          height: 65px;
          color: white;
          z-index: 1000;
        "
      >
        <div style="font-size: 20px; padding-top: 20px; text-align: center">账单详情</div>
        <van-button
          to="/WX/WD/WXWD12"
          style="
            background-color: #4b75e5;
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            border: 1px solid #4b75e5;
            margin-top: -32px;
            margin-left: 20px;
          "
        >
          <img
            src="@/assets/tb166.svg"
            style="width: 35px; height: 35px; margin-top: 3px; margin-left: -20px"
            alt=""
          />
        </van-button>
      </div>

      <div>
        <van-loading v-if="loadings" type="spinner" style="margin-top: 75px; text-align: center" />
      </div>
      <div v-if="jsonData.length == 0" style="margin-top: 30%; color: gray; text-align: center">
        暂无数据
      </div>
      <div style="margin-top: 75px; margin-bottom: 20%">
        <!--        遍历-->
        <van-cell-group
          v-for="(item, index1) in jsonData"
          style="margin-left: 20px; margin-right: 20px"
          inset
        >
          <van-cell>
            <div style="margin-left: 20px; margin-top: 10px">
              <div style="font-size: 16px; font-weight: bold">{{ item.htName }}</div>
              <div style="font-size: 13px; font-weight: bold">客户名称：{{ item.khName }}</div>
              <div style="font-size: 12px; color: rgb(128, 128, 128)">
                账单持有人：{{ user.getUsername }}
              </div>
              <div style="font-size: 12px; color: rgb(128, 128, 128)">{{ item.gsName }}</div>
              <van-divider style="margin-top: 5px" />
              <!--              下面list数据-->
              <div>
                <div v-for="(item1, index1) in item.listData" style="margin-top: 7px">
                  <van-checkbox v-model="item1.reserve5" @change="itemChange(item, item1)">
                    <div style="display: flex">
                      <div style="width: 80px">
                        <span style="color: #e7a748; margin-left: 2px">{{ item1.startTime }}</span>
                      </div>
                      <div style="width: 20px; text-align: center">至</div>
                      <div style="width: 85px">
                        <span style="color: #e7a748">{{ item1.endTime }}</span>
                      </div>
                      <div>
                        <span style="color: #c66060; margin-left: 10px">{{ item1.je }}元</span>
                      </div>
                    </div>
                  </van-checkbox>
                </div>
              </div>
              <van-divider style="margin-top: 10px" />
              <div style="display: flex">
                <div style="margin-top: 5px">
                  共：<span style="color: #c66060">{{ item.selectSum.toFixed(2) }}元</span>
                </div>
                <div style="margin-left: 30%">
                  <van-button
                    round
                    style="background-color: #3b67bb; color: white; margin-top: -5px"
                    @click="submits(item)"
                    >立即缴费</van-button
                  >
                </div>
              </div>
            </div>
          </van-cell>
        </van-cell-group>
      </div>
      <!--      缴费表单-->
      <div style="display: none">
        <form
          id="gatewayForm"
          name="gatewayForm"
          action="https://syb.allinpay.com/apiweb/h5unionpay/unionorder"
          method="POST"
        >
          <input id="appid" type="hidden" name="appid" />
          <input id="cusid" type="hidden" name="cusid" />
          <input id="version" type="hidden" name="version" />
          <input id="charset" type="hidden" name="charset" />
          <input id="trxamt" type="hidden" name="trxamt" />
          <input id="reqsn" type="hidden" name="reqsn" />
          <input id="randomstr" type="hidden" name="randomstr" />
          <input id="body" type="hidden" name="body" />
          <input id="validtime" type="hidden" name="validtime" />
          <input id="remark" type="hidden" name="remark" />
          <input id="returl" type="hidden" name="returl" />
          <input id="notify_url" type="hidden" name="notify_url" />
          <input id="signtype" type="hidden" name="signtype" />
          <input id="sign" type="hidden" name="sign" />
        </form>
      </div>
    </van-list>
  </div>
</template>

<style lang="stylus" scoped>
.page-main

  .working-list
    .item1
      padding-top 0px
      padding-bottom 0px
    .title1
      color #003586
      font-weight bolder
      font-size 13px
    .titles
      color #161718
      font-weight bolder
      font-size 13px
    .titless
      color #161718
      font-weight bolder
      font-size 17px
    .title2
      color #808080
      font-size 13px
    padding 4px
    margin-bottom 48px
    .van-tag
      margin-left 5px
      font-size 12px
      padding 5px
    .btn1
      background-color #038008
      border-radius 5px
      margin-left 5px
    .btn0
      background-color #ff8d1a
      border-radius 5px
      margin-left 5px
    .class1
      background-color #99bcf1
      border-radius 5px
    .class2
      background-color #f19999
      border-radius 5px
    .class3
      background-color #99a6f1
      border-radius 5px
    .card-item
      margin 8px
      background-color white

      .item-value
        display flex
        justify-content space-between
        overflow hidden
        text-overflow ellipsis
        word-break keep-all
        white-space nowrap
        background-color transparent
        .group1
          display flex
          flex-direction row
          justify-content space-between

  .bottom-buttons
    position fixed
    bottom 12px
    left auto
    width 100%
    max-width var(--max-width)
</style>
